package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lzq
 * @data 2023/5/2 20:51
 */
@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {


    @Autowired
    private WmNewsService wmNewsService;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmSensitiveService wmSensitiveService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Tess4jClient tess4jClient;
    /**
     * 文章审核
     * @param id  自媒体文章id
     */
    @Override
    @Async //被异步调用方法
    public void autoScanWmNews(Integer id) {
        log.info("异步调用开始了");
        //查询文章
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章是否是待审核状态
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //获取图片和文本内容
            Map<String, Object> imagesAndText = getImagesAndText(wmNews);
            //自定义管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) imagesAndText.get("text"), wmNews);
            if(!isSensitive) return;

            //文本内容文字审核
            //Boolean flagText=isFlagText((String)imagesAndText.get("text"),wmNews);
            Boolean flagText=true;
            if (!flagText){
                return;
            }
            //图片审核
            //Boolean flagImages=isFlagImages((ArrayList<String>) imagesAndText.get("images"),wmNews);
            Boolean flagImages=true;
            if (!flagImages)return;
            //审核全部通过,同步app端文章(app端保存成功返回articleId回填)
            ResponseResult responseResult = saveArticle(wmNews);
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews((short) 9,wmNews,"审核成功");
        }
    }

    /**
     * 自定义自管理的敏感词过滤
     * @param text
     * @param wmNews
     * @return
     */
    public boolean handleSensitiveScan(String text, WmNews wmNews) {
        boolean flag = true;
        //先查询缓存有没有数据
        List<WmSensitive> wmSensitives = (List<WmSensitive>) redisTemplate.opsForValue().get("wmSensitives");
        if (wmSensitives==null){
            //缓存没数据,查询数据库敏感词对象
             wmSensitives = wmSensitiveService.list();
             //存入缓存
            redisTemplate.opsForValue().set("wmSensitives",wmSensitives);
        }

        //查询具体铭感词
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词汇到工具中
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text+"-"+wmNews.getTitle());
        if (map.size()>0){
            updateWmNews((short) 2,wmNews,"当前文章中存在违规内容"+map);
            flag = false;
        }
        return flag;
    }

    /**
     * 同步app端文章(修改或保存)
     * @param wmNews
     */
    public ResponseResult saveArticle(WmNews wmNews) {
        //拷贝属性到dto
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        //补全属性AuthorId(作者)
        Integer id = wmNews.getUserId();
        dto.setAuthorId((long)id);
        //补全属性AuthorName
        WmUser wmUser = wmUserMapper.selectById(id);
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }

        //补全属性ChannelName
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        //补全属性Layout
        Short type = wmNews.getType();
        dto.setLayout(type);
        dto.setCreatedTime(new Date());
        //设置app端文章id
        if (wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }
        //调用article保存或修改文章接口
        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        return responseResult;
    }


    /**
     *   图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean isFlagImages(ArrayList<String> images, WmNews wmNews) {
        Boolean flag=true;
        //数据校验
        if (images==null){
            return flag;
        }
        //创建集合(元素为字节数组)
        ArrayList<byte[]> byteList = new ArrayList<>();
        //图片去重
        images= (ArrayList<String>) images.stream().distinct().collect(Collectors.toList());
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片识别文字审核---begin-----

                //从byte[]转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字
                String result = tess4jClient.doOCR(imageFile);

                //审核是否包含自管理的敏感词
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }

                //图片识别文字审核---end-----
                byteList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //图片下载

        try {
            //审核
            Map map = greenImageScan.imageScan(byteList);
            if (map!=null){
                if (map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews((short) 2,wmNews,"审核失败");
                }
                if (map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews((short) 3,wmNews,"内容不确定,转人工审核");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 文本内容文字审核
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean isFlagText(String text, WmNews wmNews) {
        Boolean flag=true;
        //参数校验
        if ((wmNews.getTitle()+"-"+text).length()==0){
            return flag;
        }
        try {
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + "-" + text);
            if (map!=null){
                //审核失败
                if (map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews((short) 2,wmNews,"审核失败");
                }
                if (map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews((short) 3,wmNews,"内容不确定,转人工审核");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 对审核结果修改文章
     * @param status
     * @param wmNews
     * @param reason
     */
    private void updateWmNews(Short status, WmNews wmNews, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 获取内容和图片
     * @param wmNews
     */
    private Map<String, Object> getImagesAndText(WmNews wmNews) {
        String content = wmNews.getContent();
        StringBuffer buffer = new StringBuffer();
        ArrayList<String> images = new ArrayList<>();
        //判断content文本是否为空
        if (StringUtils.isNotBlank(content)){
            List<Map> maps = JSONArray.parseArray(content, Map.class);
            for (Map map : maps) {
                //收集内容文本
                if (map.get("type").equals("text")){
                    String text = (String) map.get("value");
                    buffer.append(text);
                }
                //收集内容图片
                if (map.get("type").equals("images")){
                    String url = (String) map.get("value");
                    images.add(url);
                }
            }
            //收集封面图片
            if (StringUtils.isNotBlank(wmNews.getImages())){
                String imagesStr = wmNews.getImages();
                String[] split = imagesStr.split(",");
                //将数组数据拷贝到集合
                images.addAll(Arrays.asList(split));
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("text",buffer.toString());
        map.put("images",images);
        return map;
    }
}
